package com.coder520.poi_hibernate.user.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.coder520.poi_hibernate.user.entity.User;

@Repository
public class UserDaoImpl  implements UserDao {
//	注入sessionfactory
	@Resource(name="sessionFactory")
	private SessionFactory sessionFactory;
	
	@Override	
	public User selectUserById(Integer id) {
		String hql="from User u where id=?";
		Query query=sessionFactory.openSession().createQuery(hql);
		query.setParameter(0, id);
		User user=(User) query.uniqueResult();
		return user;
	}

	@Override
	public List<User> selectAllUser() {
		// TODO Auto-generated method stub
		String hql="select u from User u";
		Query query=sessionFactory.openSession().createQuery(hql);
		List<User> users=query.list();
		return users;
		
	}

	@Override
	public void saveUser(User user) {
		// TODO Auto-generated method stub
		System.out.println(user);
		Session session=sessionFactory.openSession();
		try {
			session.save(user);
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			session.flush();
		}
	}
	
	@Override
		public List<Integer > getId() {
			// TODO Auto-generated method stub
		String hql="select u.id from User u";
		Query query=sessionFactory.openSession().createQuery(hql);
		List<Integer> ids=query.list();
		return ids;
		}

	@Override
	public void updateUser(User user) {
		// TODO Auto-generated method stub
		Session session=sessionFactory.openSession();
		try {
			session.update(user);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			session.flush();
		}
		
	}

	@Override
	public void saveOrUpdate(User user) {
		// TODO Auto-generated method stub
		Session session=sessionFactory.openSession();
		try {
			session.saveOrUpdate(user);
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
		session.flush();
		}
	}
}
